package com.gome.ocean.controller.websql;

import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.rmi.RemoteException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.apache.http.client.methods.HttpGet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.sql.ast.SQLStatement;
import com.alibaba.druid.sql.ast.statement.SQLSelectStatement;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gome.architect.sharpeye.client.kafka.support.KafkaMessageHandler;
import com.gome.architect.sharpeye.client.util.json.handler.JsonHandler;
import com.gome.framework.AppContext;
import com.gome.framework.Env;
import com.gome.framework.util.DateUtil;
import com.gome.ocean.common.constants.Constants;
import com.gome.ocean.common.constants.WebSqlContants;
import com.gome.ocean.common.enums.DataBaseType;
import com.gome.ocean.common.enums.DataSource;
import com.gome.ocean.common.exception.CommonDataBaseException;
import com.gome.ocean.common.utils.GddlParseHelper;
import com.gome.ocean.common.utils.HttpClientUtil;
import com.gome.ocean.common.utils.JsonUtil;
import com.gome.ocean.common.utils.ResponsePage;
import com.gome.ocean.dao.model.authority.GSystemUpdateLog;
import com.gome.ocean.dao.model.datasource.SQLUploadBean;
import com.gome.ocean.dao.model.dsm.CommonDataBase;
import com.gome.ocean.dao.model.dsm.CommonDataBaseDetail;
import com.gome.ocean.dao.model.elasticsearch.SqlAudit;
import com.gome.ocean.dao.model.websql.DBANotice;
import com.gome.ocean.dao.model.websql.DataBaseVO;
import com.gome.ocean.dao.model.websql.OpenTableStruct;
import com.gome.ocean.dao.model.websql.PostChangeVO;
import com.gome.ocean.dao.model.websql.TableVO;
import com.gome.ocean.dao.websql.WebSqlEngine;
import com.gome.ocean.service.authority.SystemUpdateLogService;
import com.gome.ocean.service.base.AuthorityBaseController;
import com.gome.ocean.service.datax.ISQLUploadService;
import com.gome.ocean.service.elasticsearch.IElasticSearchService;
import com.gome.ocean.service.websql.CommonDataSourceService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * Created by liuqingxia on 2016/5/18.
 */
@Controller
@RequestMapping("/websql")
public class WebSqlController extends AuthorityBaseController {

    private static final Logger              LOG            = LoggerFactory.getLogger(WebSqlController.class);
    private static final KafkaMessageHandler messageHandler = KafkaMessageHandler.create();
    private static final String              ES_INDEX       = "sql_audit_log-*";
    private static final String              ES_TYPE        = "logs";

    @Autowired
    private IElasticSearchService   elasticSearchService;
    @Autowired
    private CommonDataSourceService commonDataSourceService;
    @Autowired
    private WebSqlEngine            webSqlEngine;
    @Autowired
    private SystemUpdateLogService  systemUpdateLogService;
    @Autowired
    private ISQLUploadService       uploadService;

    private void getLogs(ModelAndView mav) {
        List<GSystemUpdateLog> sysLists = Lists.newArrayList();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("logStatus", 2);
        param.put("logScope", Constants.SCOPE_WEBSQL_PAGE);
        String latelyTime = systemUpdateLogService.findMaxTimeByStatusAndScope(param);
        if (StringUtils.isNotBlank(latelyTime)) {
            mav.addObject("latelyTime", latelyTime);
            param.put("addTimeNode", latelyTime);
            sysLists = systemUpdateLogService.findLatelySysLogByStatusAndScope(param);
        }
        mav.addObject("gSystemUpdateLogs", sysLists);
    }

    private void insertSQLUpload(Long dataId, String dbName, String baseType, String sql, Map<String, Object> resultMap,
                                 CommonDataBaseDetail dataBaseDetail, Exception ex) {
        try {
            SQLStatement sqlStatement = GddlParseHelper.parseStatement(sql, dataBaseDetail.getDataBaseType());
            if (sqlStatement instanceof SQLSelectStatement) {
                LOG.error(ex.getMessage(), ex);
                resultMap.put("success", false);
                resultMap.put("failure", true);
                resultMap.put("root", ex.getMessage());
            } else {
                SQLUploadBean bean = new SQLUploadBean();
                bean.setAdId(dataId);
                Long sqlId = new Date().getTime();
                bean.setSqlId(sqlId);
                String commitEmail = this.getCurrentUserObj().getEmail();
                bean.setEmail(commitEmail);
                try {
                    bean.setEdept(this.getDepartMentByAccount(commitEmail.split("@")[0]));
                } catch (RemoteException e1) {
                    resultMap.put("success", false);
                    resultMap.put("failure", false);
                    resultMap.put("root", "您好,远程调用接口异常,请联系管理人员及时处理!");
                }
                bean.setSqlType(baseType.toLowerCase());
                if (StringUtils.isNotEmpty(dbName)) {
                    bean.setDbName(dbName);
                }
                bean.setUploadType("text");
                bean.setAppVersion("V1.0.0");
                bean.setSqlText(sql);
                bean.setSqlBackup("");
                Date date = new Date();
                bean.setCreateTime(date);
                bean.setAstatus("0");
                bean.setUsages("暂无");
                bean.setProject(this.getCurrentUserProjects().get(0));
                boolean flag = uploadService.insert(bean);
                if (flag) {
                    resultMap.put("success", false);
                    resultMap.put("failure", true);
                    resultMap.put("root",
                        "您好,因为您执行的sql : " + sql + ";没有权限操作,故我们已将您的执行语句提交到菜单栏【SQL执行】中的审核页面,请您及时处理,谢谢!");
                } else {
                    resultMap.put("success", false);
                    resultMap.put("failure", false);
                    resultMap.put("root", "您好,您没有权限操作,请重新处理并检查执行语句!");
                }
            }
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultMap.put("success", false);
            resultMap.put("failure", true);
            resultMap.put("root", e.getMessage());
        }
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String toIndexPage() {
        return "websql/index";
    }

    @RequestMapping(value = "/toDataSourceList", method = RequestMethod.GET)
    public ModelAndView toDataSourceList(ModelAndView mav, HttpServletRequest request) {
        List<String> projectNames = super.getCurrentUserProjects();
        Env env = AppContext.getEnv();
        String envirVal = env.get("environValue");
        mav.getModel().put("smsLoginDiamondValue", envirVal);
        String email = super.getCurrentUser();
        try {
            List<CommonDataBase> allDataBaseMaps = new ArrayList<CommonDataBase>();
            allDataBaseMaps = commonDataSourceService.getDataBaseListsByHttp(allDataBaseMaps,
                email,
                this.getDBAInterfaceIp(),
                this.getDiffEnvironmentValue());
            mav.addObject("dataSourceMaps", allDataBaseMaps);
            Map<DataSource, Set<CommonDataBase>> dataSourceMaps = commonDataSourceService
                .getAllDataSource(projectNames);
            mav.addObject("dataSourceMapsLocal", dataSourceMaps);
        } catch (CommonDataBaseException e) {
            LOG.error(e.toString());
            mav.setViewName("404");
        }
        mav.setViewName("gmwebsql/databaselist");
        return mav;
    }

    @RequestMapping(value = "/gmwebsql/index", method = RequestMethod.GET)
    public ModelAndView toGomeWebSqlIndex(ModelAndView mav, Long dataBaseId, Long dataSourceId, String baseType,
                                          Integer dataSource, HttpServletRequest request) {
        mav.addObject("isLocal", request.getParameter("isLocal"));
        mav.addObject("dataBaseId", dataBaseId);
        mav.addObject("dataSourceId", dataSourceId);
        mav.addObject("baseType", baseType);
        mav.addObject("dataSource", dataSource);
        mav.setViewName("gmwebsql/index");
        return mav;
    }

    @RequestMapping(value = "/g_websql_index", method = RequestMethod.GET)
    public ModelAndView toGwebsqlIndexPage(ModelAndView mav, Long dataBaseId, Long dataSourceId, String baseType,
                                           Integer dataSource, HttpServletRequest request) {
        String email = super.getCurrentUser();
        String isLocal = request.getParameter("isLocal");
        try {
            CommonDataBaseDetail dataBaseDetail = new CommonDataBaseDetail();
            if ("isLocal".equals(isLocal)) {
                mav.addObject("isLocal", isLocal);
                dataBaseDetail = commonDataSourceService.findDataBase(dataBaseId,
                    dataSourceId,
                    DataSource.getDataBaseType(dataSource),
                    DataBaseType.getDataBaseType(baseType));
            } else {
                dataBaseDetail = commonDataSourceService.getSingleDataBaseByHttp(dataSourceId,
                    DataBaseType.getDataBaseType(baseType.toLowerCase()),
                    email,
                    this.getDBAInterfaceIp(),
                    this.getDiffEnvironmentValue());
            }
            // 所属项目组
            List<String> userContainsProject = this.getCurrentUserProjects();
            List<Map<String, Object>> proLists = Lists.newArrayList();
            if (userContainsProject != null && userContainsProject.size() > 0) {
                for (String uPro : userContainsProject) {
                    Map<String, Object> map = Maps.newHashMap();
                    map.put("data", uPro);
                    map.put("label", uPro);
                    proLists.add(map);
                }
            } else {
                Map<String, Object> map = Maps.newHashMap();
                map.put("data", "");
                map.put("label", "");
                proLists.add(map);
            }
            mav.addObject("proLists", JSON.toJSONString(proLists));
            mav.addObject("dataBaseDetail", dataBaseDetail);
            mav.addObject("dataBaseId", dataBaseId);
            mav.addObject("dataSourceId", dataSourceId);
            mav.addObject("baseType", baseType);
            mav.addObject("dataSource", dataSource);
            mav.addObject("envirType", this.getDiffEnvironmentValue());
            mav.addObject("current_user_email", email);
        } catch (Exception e) {
            LOG.error(e.toString());
            mav.setViewName("404");
        }
        getLogs(mav);
        mav.setViewName("gmwebsql/main");
        return mav;
    }

    @RequestMapping(value = "/gmwebsql/welcome", method = RequestMethod.GET)
    public ModelAndView toOceanWebSqlIndexPage(ModelAndView mav, Long dataBaseId, Long dataSourceId, String baseType,
                                               Integer dataSource, HttpServletRequest request) {
        String email = super.getCurrentUser();
        String isLocal = request.getParameter("isLocal");
        try {
            CommonDataBaseDetail dataBaseDetail = new CommonDataBaseDetail();
            if ("isLocal".equals(isLocal)) {
                mav.addObject("isLocal", isLocal);
                dataBaseDetail = commonDataSourceService.findDataBase(dataBaseId,
                    dataSourceId,
                    DataSource.getDataBaseType(dataSource),
                    DataBaseType.getDataBaseType(baseType));
            } else {
                dataBaseDetail = commonDataSourceService.getSingleDataBaseByHttp(dataSourceId,
                    DataBaseType.getDataBaseType(baseType.toLowerCase()),
                    email,
                    this.getDBAInterfaceIp(),
                    this.getDiffEnvironmentValue());
            }
            Map<String, Object> versionMaps = webSqlEngine.getDataBaseInfo(dataBaseDetail);
            mav.addObject("versionMaps", versionMaps);
            mav.addObject("dataBaseId", dataBaseId);
            mav.addObject("dataSourceId", dataSourceId);
            mav.addObject("baseType", baseType);
            mav.addObject("dataSource", dataSource);
        } catch (Exception e) {
            LOG.error(e.toString());
            mav.setViewName("404");
        }
        mav.setViewName("gmwebsql/welcome");
        return mav;
    }

    @RequestMapping(value = "/gmwebsql/multiSqlWindow", method = RequestMethod.GET)
    public ModelAndView toMultiSqlWindowPage(ModelAndView mav, Long dataBaseId, Long dataSourceId, String baseType,
                                             Integer dataSource, String dbName, String objectName, String operation,
                                             HttpServletRequest request) throws SQLException {
        String email = super.getCurrentUser();
        String isLocal = request.getParameter("isLocal");
        try {
            CommonDataBaseDetail dataBaseDetail = new CommonDataBaseDetail();
            if ("isLocal".equals(isLocal)) {
                mav.addObject("isLocal", isLocal);
                dataBaseDetail = commonDataSourceService.findDataBase(dataBaseId,
                    dataSourceId,
                    DataSource.getDataBaseType(dataSource),
                    DataBaseType.getDataBaseType(baseType));
            } else {
                dataBaseDetail = commonDataSourceService.getSingleDataBaseByHttp(dataSourceId,
                    DataBaseType.getDataBaseType(baseType.toLowerCase()),
                    email,
                    this.getDBAInterfaceIp(),
                    this.getDiffEnvironmentValue());
            }
            Set<OpenTableStruct> tableStruct = Sets.newLinkedHashSet();
            if (operation.equals("add")) {
                OpenTableStruct struct = new OpenTableStruct();
                struct.setPrikey(true);
                struct.setName("id");
                tableStruct.add(struct);
            } else {
                Set<OpenTableStruct> tableStructIndex = Sets.newLinkedHashSet();
                Set<OpenTableStruct> tableStructData = Sets.newLinkedHashSet();
                List<TableVO> columnLists = webSqlEngine.getTableColumnDetail(dataBaseDetail, dbName, objectName);
                List<TableVO> indexLists = webSqlEngine.getTableIndexDetail(dataBaseDetail, dbName, objectName);
                for (TableVO index : indexLists) {
                    OpenTableStruct tableStr = new OpenTableStruct();
                    String[] indexName = index.getRealText().split("（");
                    tableStr.setPrikey(true);
                    tableStr.setName(indexName[1].split("）")[0]);
                    tableStructIndex.add(tableStr);
                }
                for (TableVO column : columnLists) {
                    OpenTableStruct tableStr = new OpenTableStruct();
                    for (OpenTableStruct tableIndex : tableStructIndex) {
                        if (!tableIndex.getName().equals(column.getRealName())) {
                            tableStr.setName(column.getRealName());
                            tableStructData.add(tableStr);
                        }
                    }

                }
                tableStruct.addAll(tableStructIndex);
                tableStruct.addAll(tableStructData);
            }
            mav.addObject("tableStruct", JSON.toJSONString(tableStruct));
            mav.addObject("dataBaseDetail", dataBaseDetail);
            mav.addObject("dataBaseId", dataBaseId);
            mav.addObject("dataSourceId", dataSourceId);
            mav.addObject("baseType", baseType);
            mav.addObject("dataSource", dataSource);
            mav.addObject("dbName", dbName);
            mav.addObject("objectName", objectName);
            mav.addObject("operation", operation);
        } catch (CommonDataBaseException e) {
            LOG.error(e.toString());
            mav.setViewName("404");
        }
        mav.setViewName("gmwebsql/multiSqlWindow");
        return mav;
    }

    @RequestMapping("/gwebsql/ajaxNewSqlEditorPanel")
    @ResponseBody
    public Map<String, Object> ajaxNewSqlEditorPanel() {
        Map<String, Object> panelMap = Maps.newHashMap();
        panelMap.put("success", true);
        panelMap.put("root", 27123);
        return panelMap;
    }

    @RequestMapping(value = "/sql", method = RequestMethod.GET)
    public ModelAndView toSqlPage(ModelAndView mav, HttpServletRequest request) {
        List<String> projectNames = super.getCurrentUserProjects();
        Env env = AppContext.getEnv();
        String envirVal = env.get("environValue");
        mav.getModel().put("smsLoginDiamondValue", envirVal);
        String email = super.getCurrentUser();
        try {
            List<CommonDataBase> allDataBaseMaps = new ArrayList<CommonDataBase>();
            allDataBaseMaps = commonDataSourceService.getDataBaseListsByHttp(allDataBaseMaps,
                email,
                this.getDBAInterfaceIp(),
                this.getDiffEnvironmentValue());
            mav.addObject("dataSourceMaps", allDataBaseMaps);
            // 本地
            Map<DataSource, Set<CommonDataBase>> dataSourceMaps = commonDataSourceService
                .getAllDataSource(projectNames);
            mav.addObject("dataSourceMapsLocal", dataSourceMaps);
        } catch (CommonDataBaseException e) {
            LOG.error(e.toString());
            mav.setViewName("404");
        }
        mav.setViewName("websql/sql");
        return mav;
    }

    @RequestMapping(value = "/executeSQL", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> executeSQL(HttpServletRequest request, Long dataId, String sql, String baseType,
                                          Long dataSourceId, Integer dataSource, String dbName, Integer pageNum,
                                          Integer pageSize) {
        Map<String, Object> resultMap = Maps.newHashMap();
        String email = super.getCurrentUser();
        String isLocal = request.getParameter("isLocal") == null ? "false" : request.getParameter("isLocal");
        CommonDataBaseDetail dataBaseDetail = new CommonDataBaseDetail();
        try {
            if ("isLocal".equals(isLocal)) {
                resultMap.put("isLocal", isLocal);
                dataBaseDetail = commonDataSourceService.findDataBase(dataId,
                    dataSourceId,
                    DataSource.getDataBaseType(dataSource),
                    DataBaseType.getDataBaseType(baseType));
            } else {
                dataBaseDetail = commonDataSourceService.getSingleDataBaseByHttp(dataSourceId,
                    DataBaseType.getDataBaseType(baseType.toLowerCase()),
                    email,
                    this.getDBAInterfaceIp(),
                    this.getDiffEnvironmentValue());
            }

            Object result = webSqlEngine.select(dataBaseDetail, dbName, sql, pageNum, pageSize);
            if (result instanceof String) {
                resultMap.put("failure", true);
            } else {
                resultMap.put("success", true);
                final SqlAudit sqlAudit = new SqlAudit();
                sqlAudit.setResult(JsonUtil.toJSON(result));
                sqlAudit.setSearchTime(new Date());
                sqlAudit.setSearchSql(sql);
                sqlAudit.setSearchIp(getIpAddr(request));
                sqlAudit.setSearchUser(getCurrentUser());
                sqlAudit.setEnvironValue(AppContext.getEnv().getProperty("environValue"));
                messageHandler.sendKafkaMessage(sqlAudit, new JsonHandler() {

                    @Override
                    public String toJson(Object arg0) {
                        return JsonUtil.toJSON(DateUtil.DATE_FORMAT_FULL_STRING, sqlAudit);
                    }
                });
            }
            resultMap.put("root", result);
            return resultMap;
        } catch (Exception e) {
            if ("isLocal".equals(isLocal)) {
                LOG.error(e.getMessage(), e);
                resultMap.put("success", false);
                resultMap.put("failure", true);
                resultMap.put("root", e.getMessage());
                return resultMap;
            } else {
                this.insertSQLUpload(dataId, dbName, baseType, sql, resultMap, dataBaseDetail, e);
                return resultMap;
            }
        }
    }

    @RequestMapping(value = "/postChange", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> postChange(HttpServletRequest request, Long dataId, String sql, String baseType,
                                          Long dataSourceId, Integer dataSource, String dbName) {
        Map<String, Object> resultMap = Maps.newHashMap();
        String email = super.getCurrentUser();
        String isLocal = request.getParameter("isLocal") == null ? "false" : request.getParameter("isLocal");
        CommonDataBaseDetail dataBaseDetail = new CommonDataBaseDetail();
        try {
            if ("isLocal".equals(isLocal)) {
                resultMap.put("isLocal", isLocal);
                dataBaseDetail = commonDataSourceService.findDataBase(dataId,
                    dataSourceId,
                    DataSource.getDataBaseType(dataSource),
                    DataBaseType.getDataBaseType(baseType));
            } else {
                dataBaseDetail = commonDataSourceService.getSingleDataBaseByHttp(dataSourceId,
                    DataBaseType.getDataBaseType(baseType.toLowerCase()),
                    email,
                    this.getDBAInterfaceIp(),
                    this.getDiffEnvironmentValue());
            }
            Object result = webSqlEngine.execute(dataBaseDetail, dbName, sql);
            if (result instanceof String) {
                resultMap.put("failure", true);
                resultMap.put("success", false);
            } else {
                resultMap.put("success", true);
                resultMap.put("failure", false);
                final SqlAudit sqlAudit = new SqlAudit();
                sqlAudit.setResult(JsonUtil.toJSON(result));
                sqlAudit.setSearchTime(new Date());
                sqlAudit.setSearchSql(sql);
                sqlAudit.setSearchIp(getIpAddr(request));
                sqlAudit.setSearchUser(getCurrentUser());
                sqlAudit.setEnvironValue(AppContext.getEnv().getProperty("environValue"));
                messageHandler.sendKafkaMessage(sqlAudit, new JsonHandler() {

                    @Override
                    public String toJson(Object arg0) {
                        return JsonUtil.toJSON(DateUtil.DATE_FORMAT_FULL_STRING, sqlAudit);
                    }
                });
            }
            resultMap.put("root", result);
            return resultMap;
        } catch (Exception e) {
            if ("isLocal".equals(isLocal)) {
                LOG.error(e.getMessage(), e);
                resultMap.put("failure", true);
                resultMap.put("success", false);
                resultMap.put("root", e.getMessage());
                return resultMap;
            } else {
                List<PostChangeVO> postChangeVOs = JSONObject.parseArray(sql, PostChangeVO.class);
                StringBuilder sb = new StringBuilder();
                for (PostChangeVO postChangeVO : postChangeVOs) {
                    sb.append(postChangeVO.getSql());
                }
                this.insertSQLUpload(dataId, dbName, baseType, sb.toString(), resultMap, dataBaseDetail, e);
                return resultMap;
            }

        }
    }

    @RequestMapping(value = "/getSqlPlan", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getSqlPlan(HttpServletRequest request, Long dataId, String sql, String baseType,
                                          Long dataSourceId, Integer dataSource, String dbName) {
        Map<String, Object> resultMap = Maps.newHashMap();

        String email = super.getCurrentUser();

        String isLocal = request.getParameter("isLocal");
        try {
            CommonDataBaseDetail dataBaseDetail = new CommonDataBaseDetail();
            if ("isLocal".equals(isLocal)) {
                resultMap.put("isLocal", isLocal);
                dataBaseDetail = commonDataSourceService.findDataBase(dataId,
                    dataSourceId,
                    DataSource.getDataBaseType(dataSource),
                    DataBaseType.getDataBaseType(baseType));
            } else {
                dataBaseDetail = commonDataSourceService.getSingleDataBaseByHttp(dataSourceId,
                    DataBaseType.getDataBaseType(baseType.toLowerCase()),
                    email,
                    this.getDBAInterfaceIp(),
                    this.getDiffEnvironmentValue());
            }
            Object result = webSqlEngine.getSqlPlan(dataBaseDetail, dbName, sql);
            if (result instanceof String) {
                resultMap.put("failure", true);
            } else {
                resultMap.put("success", true);
            }
            resultMap.put("root", result);
            return resultMap;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            resultMap.put("success", true);
            resultMap.put("root", e.getMessage());
            return resultMap;
        }
    }

    @RequestMapping("/getAllDbTables")
    @ResponseBody
    public Map<String, Object> getAllDbTables(HttpServletRequest request, String baseType, String dataId,
                                              String dataSourceId, String dataSource, String type, String name,
                                              String dbName) {
        Map<String, Object> resultMap = Maps.newHashMap();

        String email = super.getCurrentUser();

        String isLocal = request.getParameter("isLocal") == null ? "false" : request.getParameter("isLocal");
        try {
            String likeTableName = request.getParameter("likeTableName");
            CommonDataBaseDetail dataBaseDetail = new CommonDataBaseDetail();
            if ("isLocal".equals(isLocal)) {
                resultMap.put("isLocal", isLocal);
                dataBaseDetail = commonDataSourceService.findDataBase(Long.parseLong(dataId),
                    Long.parseLong(dataSourceId),
                    DataSource.getDataBaseType(Integer.parseInt(dataSource)),
                    DataBaseType.getDataBaseType(baseType));
            } else {
                dataBaseDetail = commonDataSourceService.getSingleDataBaseByHttp(Long.parseLong(dataSourceId),
                    DataBaseType.getDataBaseType(baseType.toLowerCase()),
                    email,
                    this.getDBAInterfaceIp(),
                    this.getDiffEnvironmentValue());
            }
            if (dataBaseDetail == null) {
                resultMap.put("root", "参数错误!");
                resultMap.put("failure", true);
                return resultMap;
            }
            List<TableVO> tables = null;
            if (StringUtils.isNotEmpty(type)) {
                // 获取列和索引数据
                if ("table".equals(type)) {
                    tables = webSqlEngine.getTableColumnAndIndex(dataBaseDetail, dbName, name);
                } else if ("column_group".equals(type)) {
                    tables = webSqlEngine.getTableColumnDetail(dataBaseDetail, dbName, name);
                } else if ("index_group".equals(type)) {
                    tables = webSqlEngine.getTableIndexDetail(dataBaseDetail, dbName, name);
                }
            } else {
                if (StringUtils.isEmpty(likeTableName)) {
                    tables = webSqlEngine.getTable(dataBaseDetail, dbName, new String[] { "TABLE" });
                } else {
                    tables = webSqlEngine.getLikeTable(dataBaseDetail, dbName, likeTableName, new String[] { "TABLE" });
                }
            }
            if (tables != null) {
                resultMap.put("root", tables);
                resultMap.put("success", true);
                return resultMap;
            } else {
                resultMap.put("failure", true);
                resultMap.put("root", "获取库信息错误!");
                return resultMap;
            }
        } catch (Exception e) {
            LOG.error("获取库信息错误!", e);
            resultMap.put("failure", true);
            resultMap.put("root", "获取库信息错误!");
            return resultMap;
        }
    }

    @RequestMapping("/autoCompleteTableColumns")
    @ResponseBody
    public Map<String, Object> autoCompleteTableColumns(HttpServletRequest request, String baseType, String dataId,
                                                        String dataSourceId, String dataSource, String dbName) {
        Map<String, Object> resultMap = Maps.newHashMap();

        String email = super.getCurrentUser();

        String isLocal = request.getParameter("isLocal");
        try {
            CommonDataBaseDetail dataBaseDetail = new CommonDataBaseDetail();
            if ("isLocal".equals(isLocal)) {
                resultMap.put("isLocal", isLocal);
                dataBaseDetail = commonDataSourceService.findDataBase(Long.parseLong(dataId),
                    Long.parseLong(dataSourceId),
                    DataSource.getDataBaseType(Integer.parseInt(dataSource)),
                    DataBaseType.getDataBaseType(baseType));
            } else {
                dataBaseDetail = commonDataSourceService.getSingleDataBaseByHttp(Long.parseLong(dataSourceId),
                    DataBaseType.getDataBaseType(baseType.toLowerCase()),
                    email,
                    this.getDBAInterfaceIp(),
                    this.getDiffEnvironmentValue());
            }
            if (dataBaseDetail == null) {
                resultMap.put("root", "参数错误!");
                resultMap.put("failure", true);
                return resultMap;
            }
            Map<String, Object> tableColumns = webSqlEngine.getAutoCompleteTableColumns(dataBaseDetail,
                dbName,
                new String[] { "TABLE" });
            if (tableColumns != null) {
                tableColumns.put("success", true);
                return tableColumns;
            } else {
                resultMap.put("root", "获取列信息错误!");
                resultMap.put("failure", true);
                return resultMap;
            }
        } catch (Exception e) {
            LOG.error("获取列信息错误!", e);
            resultMap.put("root", "获取列信息错误!");
            resultMap.put("failure", true);
            return resultMap;
        }
    }

    @RequestMapping("/getDataBase")
    @ResponseBody
    public Map<String, Object> getDataBase(HttpServletRequest request, String baseType, String dataId,
                                           String dataSourceId, String dataSource) {
        Map<String, Object> resultMap = Maps.newHashMap();

        String email = super.getCurrentUser();

        String isLocal = request.getParameter("isLocal");
        try {
            CommonDataBaseDetail dataBaseDetail = new CommonDataBaseDetail();
            if ("isLocal".equals(isLocal)) {
                resultMap.put("isLocal", isLocal);
                dataBaseDetail = commonDataSourceService.findDataBase(Long.parseLong(dataId),
                    Long.parseLong(dataSourceId),
                    DataSource.getDataBaseType(Integer.parseInt(dataSource)),
                    DataBaseType.getDataBaseType(baseType));
            } else {
                dataBaseDetail = commonDataSourceService.getSingleDataBaseByHttp(Long.parseLong(dataSourceId),
                    DataBaseType.getDataBaseType(baseType.toLowerCase()),
                    email,
                    this.getDBAInterfaceIp(),
                    this.getDiffEnvironmentValue());
            }
            if (dataBaseDetail == null) {
                resultMap.put("root", "参数错误!");
                resultMap.put("failure", true);
                return resultMap;
            }
            List<DataBaseVO> dataBaseLists = webSqlEngine.getDataBase(dataBaseDetail);
            if (dataBaseLists != null && dataBaseLists.size() > 0) {
                resultMap.put("root", dataBaseLists);
                resultMap.put("success", true);
                return resultMap;
            } else {
                resultMap.put("root", "获取库权限错误！请联系管理员。");
                resultMap.put("failure", true);
                return resultMap;
            }
        } catch (Exception e) {
            LOG.error("获取库权限错误!", e);
            resultMap.put("root", "获取库权限错误！请联系管理员。");
            resultMap.put("failure", true);
            return resultMap;
        }
    }

    @RequestMapping("/toAuditFind")
    public ModelAndView getSqlQueryLog(ModelAndView mav) {
        mav.setViewName("optlog/sql-query-log");
        return mav;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    @RequestMapping("/toSearchSqlLog")
    @ResponseBody
    public ResponsePage getSqlQueryLogs(HttpServletRequest req) {
        ResponsePage page = new ResponsePage();
        List<SqlAudit> sqlList = Lists.newArrayList();
        String startTime = req.getParameter("startTime");
        String endTime = req.getParameter("endTime");
        String tableName = req.getParameter("tableName");
        String fieldName = req.getParameter("fieldName");
        String fieldValue = req.getParameter("fieldValue");
        String email = req.getParameter("email");
        String environValue = req.getParameter("environValue");
        List<Map<String, Object>> list = elasticSearchService.queryListMapByFilterType(environValue,
            ES_INDEX,
            ES_TYPE,
            tableName,
            fieldName,
            fieldValue,
            email,
            startTime,
            endTime,
            getPageNum(),
            getPageSize());
        Long totalPage = 0L;
        if (list != null && list.size() > 0) {
            for (Map<String, Object> map : list) {
                if (map.containsKey("totalPage")) {
                    totalPage = Long.parseLong(map.get("totalPage").toString());
                } else {
                    SqlAudit audit = new SqlAudit();
                    audit.setResult(map.get("result").toString());
                    audit.setSearchIp(map.get("searchIp").toString());
                    audit.setSearchSql(map.get("searchSql").toString());
                    audit.setSearchUser(map.get("searchUser").toString());
                    audit.setEnvironValue(map.get("environValue").toString());
                    try {
                        audit.setSearchTime(
                            new SimpleDateFormat("yyyy-MM-dd H:m:s").parse(map.get("searchTime").toString()));
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    sqlList.add(audit);
                }

            }
        }
        page.setJustList(sqlList, "查询success");
        page.setTotal(totalPage);
        return page;
    }

    @RequestMapping("/splitSQL")
    @ResponseBody
    public Map<String, Object> splitSQL(String sqlText) {
        Map<String, Object> resultMap = Maps.newHashMap();
        if (StringUtils.isNotEmpty(sqlText)) {
            try {
                StopWatch stopWatch = new StopWatch();
                stopWatch.start();
                List<String> splitList = webSqlEngine.splitSQL(sqlText);
                stopWatch.stop();
                Map<String, Object> result = new HashMap<String, Object>();
                result.put("timeDelay", stopWatch.getTime());
                result.put("sqlList", splitList);
                resultMap.put("root", result);
                resultMap.put("success", true);
                return resultMap;
            } catch (Exception e) {
                LOG.error("split sql 错误!", e);
                resultMap.put("root", "sql语句错误请查看!sql:" + sqlText);
                resultMap.put("failure", true);
                return resultMap;
            }
        } else {
            resultMap.put("root", "sql语句错误请查看!sql:" + sqlText);
            resultMap.put("success", true);
            return resultMap;
        }
    }

    @RequestMapping("/getDataBaseStatus")
    @ResponseBody
    public Map<String, Object> getDataBaseStatus(String type, String dataId, String dataSourceId, String dataSource) {
        Map<String, Object> map = Maps.newHashMap();
        return map;
    }

    @RequestMapping("/ajaxHttpQueryNoticeResult")
    @ResponseBody
    public String ajaxHttpQueryNoticeResult(HttpServletRequest request) {
        String pageNum = request.getParameter("page");
        String pageSize = request.getParameter("limit");
        String path = WebSqlContants.getFormatParamsNoticePathStr(this.getDBAInterfaceIp(),
            Long.parseLong(pageNum),
            Long.parseLong(pageSize));
        HttpClientUtil httpClientUtil = new HttpClientUtil();
        List<DBANotice> lists = Lists.newArrayList();
        Map<String, Object> map = Maps.newHashMap();
        try {
            URL url = new URL(path);
            HttpGet httpGet = HttpClientUtil.getGetRequest();
            httpGet.setURI(url.toURI());
            String jsonNotice = httpClientUtil.executeAndGetWithFailedRetry(httpGet, 6, 10001);
            if (StringUtils.isNotEmpty(jsonNotice)) {
                lists = JSONArray.parseArray(jsonNotice, DBANotice.class);
                map.put("items", lists);
            }
        } catch (MalformedURLException | URISyntaxException e) {
            LOG.error("获取公告错误!", e);
        }
        String jsonStr = JSONObject.toJSONString(map);
        return jsonStr;
    }

}
